package com.hqyj.javaSpringBoot.modules.common.service.impl;

import com.hqyj.javaSpringBoot.modules.common.dao.ExceptionLogDao;
import com.hqyj.javaSpringBoot.modules.common.entity.ExceptionLog;
import com.hqyj.javaSpringBoot.modules.common.entity.Result;
import com.hqyj.javaSpringBoot.modules.common.service.ExceptionLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class ExceptionLogServiceImpl implements ExceptionLogService {

    @Autowired
    private ExceptionLogDao exceptionLogDao;

    @Override
    @Transactional
    public Result<ExceptionLog> insertExceptionLog(ExceptionLog exceptionLog) {
        // 因为没有使用 JPA 框架，需要手动插入日期
        exceptionLog.setCreateDate(LocalDateTime.now());

        // 利用 JDK8 新特性，先查询数据库中是否有数据，没有则插入数据
        List<ExceptionLog> exceptionLogs = Optional.ofNullable(
                exceptionLogDao.getExceptionLogsByParam(
                        exceptionLog.getPath(),
                        exceptionLog.getMethodName(),
                        exceptionLog.getExceptionType()
                )).orElse(Collections.emptyList());
        if (exceptionLogs.size() == 0) {
            exceptionLogDao.insertExceptionLog(exceptionLog);
        }

        // 返回成功
        return new Result<ExceptionLog>(Result.ResultCode.SUCCESS.code,
                "Insert Success.", exceptionLog);
    }
}
